package com.hy.frame.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.WindowManager;
import android.widget.Toast;

import java.lang.reflect.Field;

/**
 * title ToastUtil
 * author HeYan
 * time 19-7-10 上午11:09
 * desc 无
 */
public final class ToastUtil {
    private static Toast toast = null;

    public static boolean cache = true;

    public static void show(Context cxt, int strId) {
        show(cxt, cxt.getResources().getString(strId));
    }

    public static void show(Context cxt, CharSequence msg) {
        show(cxt, msg, Toast.LENGTH_SHORT);
    }

    private static Toast make(Context cxt, CharSequence msg, int duration) {
        return Toast.makeText(cxt.getApplicationContext(), "", duration);
    }

    @SuppressLint("ShowToast")
    public static void show(Context cxt, CharSequence msg, int duration) {
        try {
            if (cache && ToastUtil.toast != null) {
                ToastUtil.toast.cancel();
            }
        } catch (Exception ignored) {

        }
        try {
            //去掉应用名显示
            Toast toast = make(cxt, "", duration);
            hookToast(toast);
            toast.setText(msg);
            toast.show();
            if (cache)
                ToastUtil.toast = toast;
        } catch (Exception ignored) {

        }
    }

    /**
     * 捕获异常 （7.1.1 和 华为8.0）
     *
     * @param toast Toast
     */
    @SuppressLint("HandlerLeak")
    private static void hookToast(Toast toast) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1 || (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isHuaWei())) {
            try {
                // 获取 mTN 字段对象
                Field mTNField = Toast.class.getDeclaredField("mTN");
                mTNField.setAccessible(true);
                Object mTN = mTNField.get(toast);

                // 获取 mTN 中的 mHandler 字段对象
                Field mHandlerField = mTNField.getType().getDeclaredField("mHandler");
                mHandlerField.setAccessible(true);
                final Handler mHandler = (Handler) mHandlerField.get(mTN);

                // 偷梁换柱
                mHandlerField.set(mTN, new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 捕获这个异常，避免程序崩溃
                        try {
                            mHandler.handleMessage(msg);
                        } catch (WindowManager.BadTokenException ignored) {
                        }
                    }
                });

            } catch (IllegalAccessException | NoSuchFieldException ignored) {
            }
        }
    }

    private static boolean isHuaWei() {
        String mft = Build.MANUFACTURER;
        if (mft != null) {
            mft = mft.toLowerCase();
            return mft.equals("honor") || mft.equals("huawei");
        }
        return false;
    }
}
